﻿using DataCenter.IDataProvider;
using DataCenter.Service.Implementations;
using DataCenter.Service.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace DataCenter.App.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class CodeController : ControllerBase
    {
        //private readonly ICodeProvider codeProvider;
        private readonly IServiceProvider serviceProvider;
        private readonly ICustomerService customerService;
        public CodeController( IServiceProvider diserviceProvider, ICustomerService ctmService  )
        {
            //codeProvider= provider;
            serviceProvider=diserviceProvider;
            customerService = ctmService;
        }

        /// <summary>
        ///  测试
        /// </summary>
        /// <remarks>
        /// customerId= 70c92219-a484-1614-76ad-bdc2dbacf9af
        /// 
        /// productId= 38b69d4d-a5e5-cc50-65a1-2ba426e4a641
        /// </remarks>
        /// <param name="customerId"></param>
        /// <param name="productId"></param>
        /// <returns></returns>
        [HttpGet(nameof(GetQRCode))]
        public async Task<IActionResult> GetQRCode([FromQuery] string customerId, [FromQuery] string productId)
        {
            var customer= await  customerService.GetById(Guid.Parse(customerId));
            var dllname = customer.AppName.Replace(".dll", "");
            var codeproviders=  serviceProvider.GetServices<ICodeProvider>();
            //.Assembly.ManifestModule.Name
            var codeProvider = codeproviders.FirstOrDefault(item => item.GetType().Assembly.ManifestModule.Name == customer.AppName);
            var code=   await codeProvider.GetQRCodeAsync(customerId, productId);
            return Ok(code);
        }

        [HttpGet(nameof(GetLasterCode))]
        public async Task<IActionResult> GetLasterCode([FromQuery]string customerId, [FromQuery] string productId)
        {
            var customer = await customerService.GetById(Guid.Parse(customerId));
            var dllname = customer.AppName.Split('.')[0];
            var codeproviders = serviceProvider.GetServices<ICodeProvider>();
            var codeProvider = codeproviders.FirstOrDefault(item => item.GetType().Name == dllname);
            var code = await codeProvider.GetLasterCodeAsync(customerId, productId);
            return Ok(code);
        }
    }
}
